Loading or Saving a XAML Resource Dictionary
Here is a rudimentary example of how to load a ResourceDictionary.xaml file and then how to change it and save the changes.
1 2 3 4 5 | xmlns:sys = "clr-namespace:System;assembly=mscorlib" > < sys:String x:Key = "HW" >Hello, World</ sys:String > </ ResourceDictionary > |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | using System; using System.IO; using System.Windows; using System.Windows.Markup; namespace ReadAndWriteToXaml { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { public static ResourceDictionary Dictionary; public static String XamlFileName = "Dictionary1.xaml" ; public App() { LoadStyleDictionaryFromFile(XamlFileName); } /// <summary> /// This funtion loads a ResourceDictionary from a file at runtime /// </summary> public void LoadStyleDictionaryFromFile( string inFileName) { if (File.Exists(inFileName)) { try { using ( var fs = new FileStream(inFileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { // Read in ResourceDictionary File Dictionary = (ResourceDictionary)XamlReader.Load(fs); // Clear any previous dictionaries loaded Resources.MergedDictionaries.Clear(); // Add in newly loaded Resource Dictionary Resources.MergedDictionaries.Add(Dictionary); } } catch { // Do something here if file not found } } } private void Application_Exit_1( object sender, ExitEventArgs e) { try { Dictionary[ "HW" ] += "Hello, back!" ; StreamWriter writer = new StreamWriter(XamlFileName); XamlWriter.Save(Dictionary, writer); } catch { // Do something here if file not found } } } } |
Note: Unfortunately you cannot use two way mode when binding to DynamicResource objects, so editing the xaml file is made a bit more complex. But hopefully, this will help you get started.